namespace ScrumSprintMonitor.UI.Wpf.Converters
{
	#region #using Directives

	using System;
	using System.Globalization;
	using System.Windows;
	using System.Windows.Data;

	#endregion

	/// <summary>
	///   Aim: be able to specify margins as a percentage of parent size (L,T,R,B)
	///   Binding properties should be specified Height then Width
	/// </summary>
	public class RelativeMarginConverter : IMultiValueConverter
	{
		#region IMultiValueConverter Members

		public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
		{
			if (values.Length < 2)
			{
				return Binding.DoNothing;
			}
			if (values[0] == DependencyProperty.UnsetValue || values[1] == DependencyProperty.UnsetValue)
			{
				return Binding.DoNothing;
			}

			double height = (double) values[0] / 100, width = (double) values[1] / 100;
			var margins = parameter.ToString().Split(',').ToDouble();

			if (double.IsNaN(height))
			{
				height = 1; // fallback to margin as value if height not ok
			}
			if (double.IsNaN(width))
			{
				width = 1; // fallback to margin as value if width not ok
			}

			return new Thickness(margins[0] * width, margins[1] * height, margins[2] * width, margins[3] * height);
		}

		public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
		{
			throw new NotImplementedException();
		}

		#endregion
	}


	internal static class Extensions
	{
		public static double[] ToDouble(this string[] arr)
		{
			var dbl = new double[arr.Length];
			for (int i = 0; i < arr.Length; i++)
			{
				dbl[i] = Double.Parse(arr[i]);
			}
			return dbl;
		}
	}
}